//
//  Matcher.swift
//

import Foundation

public enum Matcher: String {
    case phone = "^1[0-9]{10}$"
    case email = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
    case password = "^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$"
    case number = "^[0-9]+$"
    case url = "[a-zA-z]+://[^\\s]*"
    
    public func evaluate(_ input: String) -> Bool {
        let predicate = NSPredicate(format: "SELF MATCHES %@", rawValue)
        return predicate.evaluate(with: input)
    }
    
    /// 匹配关键词范围
    ///
    /// - Parameters:
    ///   - keyword: 关键词
    ///   - whole: 完整字符串
    /// - Returns: 匹配的范围数组
    public static func matchesKeywordRanges(_ keyword: String, in whole: String) -> [NSRange] {
        do {
            let regEx = try NSRegularExpression(pattern: keyword, options: .caseInsensitive)
            let results = regEx.matches(in: whole, options: .reportCompletion, range: NSMakeRange(0, whole.count))
            return results.map {
                $0.range
            }
        } catch {
            return []
        }
    }
}
